<template>
  <el-card class="setting-card">
    <h2 class="title">账户设置</h2>

    <!-- 基本信息表单 -->
    <el-form
      ref="baseForm"
      :model="baseForm"
      :rules="baseRules"
      label-width="120px"
    >
      <el-form-item label="头像" prop="avatar">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :before-upload="handleBeforeAvatarUpload"
          :on-change="handleAvatarChange"
          accept="image/jpeg, image/png"
          action="#"
          :auto-upload="false"
        >
          <img
            v-if="baseForm.avatar"
            :src="baseForm.avatar"
            class="avatar-preview"
            alt="头像"
          />
          <i v-else class="el-icon-plus avatar-placeholder"></i>
        </el-upload>
        <div class="tip">建议上传1:1比例图片，支持JPG/PNG格式</div>
      </el-form-item>

      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="baseForm.nickname" placeholder="2-10位字符" />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="baseForm.email" placeholder="请输入邮箱" />
      </el-form-item>

      <el-form-item label="手机号" prop="phone">
        <el-input v-model="baseForm.phone" placeholder="11位数字" />
      </el-form-item>
      <!-- 新增：个人网站表单项 -->
      <el-form-item label="个人网站" prop="website">
        <el-input
          v-model="baseForm.website"
          placeholder="可选，如https://myblog.com"
        />
      </el-form-item>

      <!-- 新增：个人简介表单项 -->
      <el-form-item label="个人简介" prop="bio">
        <el-input
          type="textarea"
          v-model="baseForm.bio"
          placeholder="可选，最多200字"
          rows="3"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitBaseForm"
          >保存基本信息</el-button
        >
        <el-button @click="resetBaseForm">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 密码修改表单 -->
    <el-form
      ref="passwordForm"
      :model="passwordForm"
      :rules="passwordRules"
      label-width="120px"
      class="mt-30"
    >
      <el-form-item label="原密码" prop="oldPwd">
        <el-input
          type="password"
          v-model="passwordForm.oldPwd"
          placeholder="请输入原密码"
        />
      </el-form-item>

      <el-form-item label="新密码" prop="newPwd">
        <el-input
          type="password"
          v-model="passwordForm.newPwd"
          placeholder="6-20位字母数字组合"
        />
      </el-form-item>

      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          type="password"
          v-model="passwordForm.confirmPassword"
          placeholder="请重复新密码"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitPasswordForm"
          >修改密码</el-button
        >
        <el-button @click="resetPasswordForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { updateUserInfo, updatePassword } from "@/api";

export default {
  data() {
    // 基本信息验证规则
    const validateEmail = (rule, value, callback) => {
      if (!/^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/.test(value)) {
        callback(new Error("请输入正确的邮箱格式"));
      } else {
        callback();
      }
    };
    const validateWebsite = (rule, value, callback) => {
      if (value && !/^https?:\/\/.*/.test(value)) {
        callback(new Error("网站链接需以http/https开头"));
      } else {
        callback();
      }
    };

    const validatePhone = (rule, value, callback) => {
      if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error("请输入11位有效手机号"));
      } else {
        callback();
      }
    };

    return {
      // 基本信息表单数据
      baseForm: {
        avatar: null,
        nickname: "",
        email: "",
        phone: "",
        website: "", // 新增：个人网站字段
        bio: "", // 新增：个人简介字段
      },
      // 基本信息验证规则
      baseRules: {
        nickname: [
          {
            required: true,
            min: 2,
            max: 10,
            message: "2-10位字符",
            trigger: "blur",
          },
        ],
        email: [{ required: true, validator: validateEmail, trigger: "blur" }],
        phone: [{ required: true, validator: validatePhone, trigger: "blur" }],
        website: [{ validator: validateWebsite, trigger: "blur" }],
        bio: [{ max: 200, message: "简介最多200字", trigger: "blur" }],
      },

      // 密码修改表单数据
      passwordForm: {
        oldPwd: "",
        newPwd: "",
        confirmPassword: "",
      },
      // 密码验证规则
      passwordRules: {
        oldPwd: [{ required: true, message: "请输入原密码", trigger: "blur" }],
        newPwd: [
          {
            required: true,
            min: 6,
            max: 20,
            message: "6-20位字符",
            trigger: "blur",
          },
        ],
        confirmPassword: [
          { required: true, message: "请确认新密码", trigger: "blur" },
          {
            // 关键修改：使用callback传递验证结果
            validator: function (rule, value, callback) {
              if (value !== this.passwordForm.newPwd) {
                // 验证失败时调用callback传递错误
                return callback(new Error("两次输入的密码不一致"));
              }
              // 验证通过时调用空callback
              callback();
            }.bind(this),
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    // 头像上传前校验
    handleBeforeAvatarUpload(file) {
      const isImage = ["image/jpeg", "image/png"].includes(file.type);
      const isLt2M = file.size / 1024 / 1024 <= 2;

      if (!isImage) {
        this.$message.error("仅支持JPG/PNG格式图片");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("图片大小不能超过2MB");
        return false;
      }
      return true;
    },

    // 头像转换为base64
    handleAvatarChange(file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        this.baseForm.avatar = e.target.result;
      };
      reader.readAsDataURL(file.raw);
    },

    // 提交基本信息
    async submitBaseForm() {
      const userId = this.$store.state.user.id;
      this.$refs.baseForm.validate(async (valid) => {
        if (!valid) return;

        try {
          const res = await updateUserInfo({
            ...this.baseForm,
            id: userId,
          });
          console.log(res);

          if (res.data.status === 0) {
            this.$message.success("基本信息更新成功");
            // 更新Vuex中的用户信息
            this.$store.commit("setUser", {
              ...this.$store.state.user,
              ...this.baseForm,
            });
            console.log(this.$store.state.user);
          } else {
            this.$message.error(res.data.message || "更新失败，请重试");
          }
        } catch (err) {
          this.$message.error("网络请求失败");
        }
      });
    },

    // 重置基本信息表单
    resetBaseForm() {
      this.$refs.baseForm.resetFields();
    },

    // 提交密码修改
    async submitPasswordForm() {
      this.$refs.passwordForm.validate(async (valid) => {
        console.log(valid);
        if (!valid) return;
        try {
          const res = await updatePassword({
            ...this.passwordForm,
            id: this.$store.state.user.id,
          });
          if (res.data.status === 0) {
            this.$message.success("密码修改成功,即将返回登录页面");
            this.resetPasswordForm();

            setTimeout(() => {
              this.$store.dispatch("logout");
              localStorage.removeItem("token");
              this.$router.push("/login");
            }, 3000);
          } else {
            this.$message.error(res.data.message || "修改失败，请重试");
          }
        } catch (err) {
          this.$message.error("网络请求失败");
        }
      });
    },

    // 重置密码表单
    resetPasswordForm() {
      this.$refs.passwordForm.resetFields();
    },
  },
  mounted() {
    // 初始化加载用户当前信息（示例）
    this.baseForm = {
      avatar: this.$store.state.user.avatar, // 从Vuex获取当前头像
      nickname: this.$store.state.user.nickname,
      email: this.$store.state.user.email,
      phone: this.$store.state.user.phone,
      website: this.$store.state.user.website,
      bio: this.$store.state.user.bio,
    };
  },
};
</script>

<style scoped>
.setting-card {
  max-width: 600px;
  margin: 30px auto;
  padding: 20px 30px;
}

.title {
  text-align: center;
  font-size: 24px;
  margin-bottom: 30px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  width: 120px;
  height: 120px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.avatar-placeholder {
  font-size: 28px;
  color: #8c939d;
}

.avatar-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.tip {
  color: #606266;
  font-size: 12px;
  margin-top: 8px;
}

.mt-30 {
  margin-top: 30px;
}
.el-form-item textarea {
  margin-top: 8px;
}
</style>
